#!/bin/bash

scriptPath=$(dirname $0);
echo "inter packet time analysis (interpacket.eps)"

cat $scriptPath/interpacket-gnuplot.begin > interpacket.gplot
echo "" > tmp-interpacket-aggregate

numDObj=$(sqlite3 -batch trace.sqlite "select count(*) from (select * from eventsContentOnly group by substr(dataobjectId,0,40));")

i=0
for logPath in $(ls -1d */)
do
	logPath=$(echo $logPath | sed 's/\///')
	if [ -f $logPath/title ]
	then device=$(cat $logPath/title);
	else device=$logPath;
	fi

	i=$[i+1]
	sqlite3 -batch -separator ' ' trace.sqlite "SELECT e.time as t, (c.dataobjectId) as hasFile FROM eventsContentOnly as e LEFT JOIN dobjContent as c ON substr(e.dataobjectId,0,40)=c.dataobjectId WHERE e.eventName='EVENT_TYPE_DATAOBJECT_NEW' AND e.device='$device' ORDER BY t;" | awk '{if (prevTime>0) {print $1-prevTime;} prevTime=$1}' | sort -n | awk '{print $1, FNR}' > tmp-interpacket-$logPath
	PLOT=$PLOT"\"tmp-interpacket-$logPath\" using 1:(\$2/$numDObj) with linespoints ls $i t \"$device\","
	
	cat tmp-interpacket-$logPath | awk '{print $1;}' >> tmp-interpacket-aggregate
done

cat tmp-interpacket-aggregate | sort -n | awk '{print $1, FNR}' > tmp-interpacket-aggregate-cdf
PLOT=$PLOT"\"tmp-interpacket-aggregate-cdf\" using 1:(\$2/($i*$numDObj)) with linespoints ls $i+1 t \"all nodes\","

PLOT=`echo $PLOT | sed -e 's/,$//'`
echo "plot "$PLOT >> interpacket.gplot

gnuplot interpacket.gplot

rm interpacket.gplot
rm tmp-interpacket*
